import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  SearchOutlined,
  UndoOutlined,
  CheckOutlined
} from '@ant-design/icons';
import {
  Button,
  message,
  Form,
  DatePicker,
  Modal,
  Row,
  Col,
  Input,
  Popconfirm,
  Select,
  Tag,
  Tooltip, Space,
} from 'antd';
import zhCN from 'antd/es/date-picker/locale/zh_CN'; // 引入中文包
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import '@/assets/css/index.less';
import ProForm, { ProFormTextArea, ProFormText } from '@ant-design/pro-form';
import moment from 'moment';
import {
  createVoteWithOption,
  deleteVoteById,
  getVoteByVoteId,
  getVoteList,
  publishVote,
  updateVote,
} from '@/services/voteApi';
import { formatDateDayjs } from '@/utils/formatDate';
import { useModel } from 'umi';
import {LocalFormat} from "@/utils/localHelper";
import locale from "antd/es/date-picker/locale/zh_CN";
import 'moment/locale/zh-cn'
const formLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 10,
  },
};
const voteTemplate: React.FC = () => {
  const [voteForm] = Form.useForm();
  const [search_form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(40);
  const [dataArray, setDataArray] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [currentValue, setCurrentValue] = useState({});
  const [modalTitle, setModalTitle] = useState('add');
  const [publishDisable, setPublishDisable] = useState(false);
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });

  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [modalVisible, setModalVisible] = useState(false);
  const handleDelete = async (record: any) => {
    try {
      const res = await deleteVoteById({ voteId: record.id });
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败' + error.response.data.message);
    }
    queryData();
  };
  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
    setPagination({ ...pagination });
  };
  useEffect(() => {
    queryData();
  }, [page, pageSize]);
  const queryData = async () => {
    let values = search_form.getFieldsValue();
    const params = {
      page: page,
      pageSize: pageSize,
      roleId: currentUser.roleId,
      ...values,
    };
    const msg = await getVoteList(params);
    setDataArray(msg.data.list);
    setPagination({ ...pagination, total: msg.data.total });
  };

  const getVoteInfoByID = async (record) => {
    const voteInfo = await getVoteByVoteId({
      voteId: record.id,
    });
    formatDateDayjs([voteInfo.data.vote], 'startTime', 'YYYY-MM-DD');
    formatDateDayjs([voteInfo.data.vote], 'endTime', 'YYYY-MM-DD');
    const obj = { ...voteInfo.data.vote };
    voteForm.setFieldsValue({
      ...obj,
    });
    setCurrentValue(obj);
    setModalVisible(true);
  };

  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={search_form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
        >
          <Row style={{ width: '100%' }}>
            <Col span={4}>
              <Form.Item label="标题" name="title">
                <Input placeholder="请输入标题" />
              </Form.Item>
            </Col>

            <Col span={6}>
              <Form.Item label="选择状态" name="publish">
                <Select
                  allowClear
                  options={[
                    { value: true, label: '已发布' },
                    { value: false, label: '未发布' },
                  ]}
                ></Select>
              </Form.Item>
            </Col>

            <Col
              span={14}
              className="basic-search-form-submit-btn"
              style={{ display: 'flex', justifyContent: 'flex-end' }}
            >
              <Button
                onClick={() => {
                  search_form.resetFields();
                  queryData();
                }}
              >                <UndoOutlined />

                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData()}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };
  const publishFun = async () => {
    const res = await publishVote({ id: currentValue.id });
    if (res.code == '0') {
      message.success('发布成功');
      setCurrentValue({});
      setModalVisible(false);
    } else {
      message.success('发布失败');
    }
  };

  const submitVoteTemplate = async () => {
    const formValues = voteForm.getFieldsValue();
    formValues.startTime =
      formValues.startTime && moment(formValues.startTime).format('YYYY-MM-DD') + ' 00:00:00';
    formValues.endTime =
      formValues.endTime && moment(formValues.endTime).format('YYYY-MM-DD') + ' 23:59:59';
    const voteDetail = {
      anonymous: true,
      endTime: formValues.endTime,
      startTime: formValues.startTime,
      title: formValues.title,
      voteOptionStr: formValues.voteOptionStr,
    };

    if (currentValue.id) {
      voteDetail.id = currentValue.id;
      const result = await updateVote({
        voteDetail,
      });
      if (result.code === '0') {
        message.success('更新成功！');
      }
    } else {
      const result = await createVoteWithOption({
        voteDetail,
      });
      if (result.code === '0') {
        message.success('创建成功！');
      }
    }
    queryData();
  };
  const columns: ProColumns[] = [
    {
      title: '标题',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'title',
      render: (_, record) => {
        return (
          <Tooltip title={record.description} color="#108ee9" placement="rightBottom">
            {record.title}
          </Tooltip>
        );
      },
    },
    {
      title: '状态',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'publish',
      render: (_, record) => {
        if (record.publish == false) {
          return (
            <Tag color="blue" key="wfb">
              未发布
            </Tag>
          );
        } else if (record.publish == true) {
          return (
            <Tag color="green" key="yfb">
              已发布
            </Tag>
          );
        }
      },
    },
    {
      title: '发布人',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdBy',
    },

    {
      title: '创建时间',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdTime',
    },

    {
      title: '操作',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'id',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            getVoteInfoByID(record);
            setModalTitle('edit');
            setPublishDisable(false);
          }}
        >
          <Button className={'buttonMargin'} shape={'round'} type="primary" icon={<EditOutlined />}>
            编辑
          </Button>
        </a>,
        <Popconfirm title="确定是否删除?" onConfirm={() => handleDelete(record)} key="delete">
          <a style={{ color: 'red' }} key="delete">
            <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
              删除
            </Button>
          </a>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <PageContainer>
      {_initSearchForm()}
      <ProTable
        search={false}
        actionRef={actionRef}
        options={false}
        rowKey={'id'}
        tableStyle={{ textAlign: 'center' }}
        onChange={handleTableChange}
        pagination={pagination}
        dataSource={dataArray}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={(e) => {
              setModalVisible(true);
              setPublishDisable(true);
              setModalTitle('add');
              voteForm.setFieldsValue({
                title: '',
                startTime: null,
                endTime: null,
                voteOptionList: '',
              });
            }}
          >
            <PlusOutlined />
            发布投票
          </Button>,
        ]}
        columns={columns}
      ></ProTable>

      <Modal
        title={modalTitle == 'add' ? '发起投票' : '编辑投票'}
        width="600px"
        destroyOnClose
        open={modalVisible}
        key={new Date().getTime()}
        onCancel={() => {
          setModalVisible(false);
          voteForm.resetFields();
        }}
        footer={[
          <Button
            key="close"
            onClick={() => {
              setModalVisible(false);
              setCurrentValue({});
            }}
          >
            关闭
          </Button>,
          <Button
            type="primary"
            key="submit"
            onClick={() => {
              setModalVisible(false);
              submitVoteTemplate();
              setCurrentValue({});
            }}
          >
            提交
          </Button>,
          <Button
            type="primary"
            key="publish"
            disabled={publishDisable}
            onClick={() => {
              publishFun();
            }}
          >
            发布
          </Button>,
        ]}
      >
        <ProForm
          form={voteForm}
          // preserve={false}
          layout="horizontal"
          {...formLayout}
          initialValues={currentValue || {}}
          submitter={{
            render: (_, dom) => (
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <Space>
                  {/*{dom}*/}
                  {<Button onClick={() => {
                    _.reset()
                  }}><UndoOutlined />重置</Button>}
                  {<Button type={"primary"} onClick={() => {
                    _.submit()
                  }}><CheckOutlined />提交</Button>}

                </Space>
              </div>
            ),
          }}
        >
          <ProFormText
            width="md"
            name="title"
            label="投票标题"
            rules={[
              {
                required: true,
                message: '请输入标题',
              },
            ]}
          />
          <Form.Item label="开始时间" name="startTime">
            <DatePicker locale={locale} />
          </Form.Item>
          <Form.Item label="结束时间" name="endTime">
            <DatePicker locale={locale} />
          </Form.Item>
          <ProFormTextArea name="voteOptionStr" placeholder="请输入" label="候选人(用;隔开)" />
        </ProForm>
      </Modal>
    </PageContainer>
  );
};
export default voteTemplate;
